package com.qf.smsplatform.interfaces.controller;

import com.qf.smsplatform.common.exception.SmsException;
import com.qf.smsplatform.common.util.R;
import com.qf.smsplatform.interfaces.form.SmsInterfaceForm;
import com.qf.smsplatform.interfaces.service.SmsInterfaceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
public class InterfaceController {

    /**
     * 请求头信息
    private static final String[] IP_HEADERS = {
            "X-Forwarded-For",
            "Proxy-Client-IP",
            "WL-Proxy-Client-IP",
            "HTTP_X_FORWARDED_FOR",
            "HTTP_X_FORWARDED",
            "HTTP_X_CLUSTER_CLIENT_IP",
            "HTTP_CLIENT_IP",
            "HTTP_FORWARDED_FOR",
            "HTTP_FORWARDED",
            "HTTP_VIA",
            "REMOTE_ADDR"};*/

    @Value("${ip-header}")
    private String ipHeader;

    @Autowired
    private SmsInterfaceService smsInterfaceService;

    // 请服务方url地址：http://ip:port/smsInterface,客户方将下行数据发送到该url
    @PostMapping("/smsInterface")
    public R smsInterface(SmsInterfaceForm smsInterfaceForm, HttpServletRequest req){
        //1. 获取用户请求时携带的ip地址信息
        String ip = this.getReallyIpAddress(req);

        //2. 将ip地址封装到form对象中
        smsInterfaceForm.setIp(ip);

        try {
            //3. 调用service,对参数进行一些列的校验
            smsInterfaceService.checkParameters(smsInterfaceForm);
            //4. 返回结果
            return R.ok("接收成功");
        } catch (SmsException e) {
            //5. 校验未通过
            if(e.getCode() == 105 && e.getData() != null){
                // 手机号码错误,
                return R.errorData(e);
            }else{
                // 其他信息验证失败
                return R.error(e);
            }
        }


    }

    private String getReallyIpAddress(HttpServletRequest req) {
        //1. 校验使用@value注入的请求头没问题
        if(!StringUtils.isEmpty(ipHeader) && ipHeader.length() > 0){
            //2. 将字符串使用,分割获取数组,并遍历数组
            for (String header : ipHeader.split(",")) {
                // 3. 通过req对象,从请求头中获取真实的ip
                String ip = req.getHeader(header);
                //4. 判断是否真的拿到了ip地址
                if(!StringUtils.isEmpty(ip) && !"unknown".equalsIgnoreCase(ip)){
                    // 5. 获取到了真实的ip
                    return ip;
                }
            }
        }
        //6. 循环结束,没有拿到真实的ip地址,通过传统的方式获取ip
        return req.getRemoteAddr();
    }


}
